#coding:utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')


from pyzabbix import ZabbixAPI

class Zabbix(object):
    """docstring for Zabbix"""
    def __init__(self, 
        url='http://211.166.22.181', 
        user='Admin', 
        passwd='zabbix'):
        self.zapi = ZabbixAPI(url)
        try:
            self.zapi.login(user, passwd)
        except Exception as e:
            raise e

    def add_host(self, hostname, ip ,group_name, template_name):
        groupid = self.get_groups(group_name)[0]['groupid']
        templateid= self.get_teamplates(template_name)[0]['templateid']
        params = {
            "host": "{hostname}".format(hostname=hostname),
            "interfaces": [
                {
                    "type": 1,
                    "main": 1,
                    "useip": 1,
                    "ip": '{ip}'.format(ip=ip),
                    "dns": "",
                    "port": "10050"
                }
            ],
            "groups": [
                {
                    "groupid": "{groupid}".format(groupid=groupid)
                }
            ],
            "templates": [
                {
                    "templateid": "{templateid}".format(templateid=templateid)
                }
            ]
        }
        return self.zapi.host.create(**params)

    def add_group(self, group_name):
        params = { 'name' : '{group_name}'.format(group_name=group_name)}
        return self.zapi.hostgroup.create(**params)

    def get_tiggers(self, group_name=None,):
        params =  {
            "output": [
                "description",
                "priority"
            ],
            "filter": {
                "value": 1
            },
            'expandDescription' : 1
        }
        if group_name:
            params['group'] = group_name
        return self.zapi.trigger.get(**params)

    def get_groups(self, group_name=None):
        #[(group_name,group_id)]
        params = { 'output' : ['name','groupid'] }
        if group_name:
            filter = {'name' : [group_name] }
            params['filter'] = filter
        return self.zapi.hostgroup.get(**params)

    def get_teamplates(self, template_name=None):
        #template.get
        params = { 'output' : ['name','templateid'] }
        if template_name:
            filter = { 'name' : [template_name] }
            params['filter'] = filter
        return self.zapi.template.get(**params)   

    def test(self):
        params = {
            'output' : ['groupid','name']
        }
        result = self.zapi.hostgroup.get(**params)
        return result

if __name__ == '__main__':
    z = Zabbix()
    print z.add_group('jfedu webs')